package com.jy.appmarket.adapter;

import java.text.SimpleDateFormat;
import java.util.Locale;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jy.appmarket.R;
import com.jy.appmarket.activity.DownloadManagerActivity;
import com.jy.appmarket.activity.DownloadManagerActivity.DownloadItemUI;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.utils.AsyncImageLoader;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.UITools;

public class DownloadMrgAdapter extends SimpleBaseAdapter<DownloadItemUI> {
	
	public interface  DLMrgAdapterClickListener{
		void onExpandClick();
		void onAppOpenClick(DownloadItem di);
		void onDealingBtnClick(DownloadItem di);
		void onDeleteOneDlItem(final DownloadItem di);
		void onClearAllFinishTask();
	}
	
	private static String TAG = "DownloadMrgAdapter";
	
	private SimpleDateFormat mSd = new SimpleDateFormat("yyy.MM.dd",  
			Locale.CHINA);
	private DLMrgAdapterClickListener mListener = null;

	public DownloadMrgAdapter(Context context, DLMrgAdapterClickListener l) {
		super(context);
		mListener = l;
	}

	static class UnfinishSectionHolder {
		TextView sectionView;
	}
	
	static class FinishSectionHolder{
		TextView titleView;
		TextView clearView;
	}
	
	static class FinshTaskHolder{
		ImageView appIcon;
		TextView appName;
		TextView appTime;
		Button openBtn;
	}
	
	static class DealingTaskHolder{
		ImageView appIcon;
		TextView appName;
		TextView dlStatus;
		TextView dlProgress;
		ProgressBar progressBar;
		Button button;
		TextView delete;
	}
	
	@Override
	public boolean areAllItemsEnabled (){
		return false;
	}

	@Override
	public boolean isEnabled (int position){
		DownloadItemUI dlui = mList.get(position);
        return dlui.uiType == DownloadItemUI.SHOW_ALL_FINISH;

    }

	@Override
	public int getItemViewType(int position) {
		DownloadItemUI dlui = mList.get(position);
		return dlui.uiType;
	}


	@Override
	public int getViewTypeCount() {
		return 5;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		DownloadItemUI dlui = mList.get(position);
		
		if(dlui.uiType == DownloadItemUI.UNFINISH_SECTION){
			return showUnfinishSection(dlui, position, convertView, parent);
			
		}else if(dlui.uiType == DownloadItemUI.FINISH_SECTION){
			return showFinishSection(dlui, position, convertView, parent);

		}else if(dlui.uiType == DownloadItemUI.SHOW_ALL_FINISH){
			if(convertView == null){
				convertView = getInflater().inflate(R.layout.dl_mrg_show_all, parent, false);
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mListener.onExpandClick();
				}
			});
			
			return convertView;
			
		}else if(dlui.uiType == DownloadItemUI.DL_FINISH){
			return showDownloadFinishTask(dlui, position, convertView, parent);
			
		}else if(dlui.uiType == DownloadItemUI.DL_UNFINISH){
			return showDownloadDealingTask(dlui, position, convertView, parent);
		}

		return null;
	}
	
	private int getProgress(DownloadItem app) {
		long total = app.getTotalSize();
		if (total == 0) {
			total = Long.MAX_VALUE;
			LogUtil.w(TAG, "total is 0");
		}

		int per = (int) (app.getDownloadedSize() * 100.0 / total);

		if (per > 100) {
			per = 100;
		} else if (per < 0) {
			per = 0;
		}
		return per;
	}
	
	private String getProgressString(DownloadItem di){
		if(di == null){
			return "";
		}
		if(di.getTotalSize() == 0){
			return "";
		}
		String totalSizeStr = UITools.normalizationFileSize(di
				.getTotalSize());
		
		String dlSize = null;
		if(totalSizeStr.contains("M")){
			dlSize = UITools.normalizationFileSizeToM(di
				.getDownloadedSize(), false);
		}else{
			dlSize = UITools.normalizationFileSizeToK(di
					.getDownloadedSize(), false);
		}
		
		return dlSize + "/" + totalSizeStr;
	}
	
	private String getSpeedString(DownloadItem di){
		
		long speed = di.getSpeed();
		
		if(speed <= 0){
			return "0K/S";
		}
		
		if(speed > 0 && speed < 1024 * 1024){
			float kb = speed / 1024.0f;
			String skb = String.format("%.1f", kb) + "K/S";
			return skb;
		}else{
			float mb = speed / (1024.0f * 1024);
			String smb = String.format("%.1f", mb) + "M/S";
			return smb;
		}
	}
	
	
	private static int BUTTON_BLUE = 0;
	private static int BUTTON_GRAY = 1;
	private static int BUTTON_ORANGE = 2;
	
	private void setButtonParam(int type, Button btn){
		if(type == BUTTON_BLUE){
			btn.setBackgroundResource(R.drawable.download_button_blue);
			btn.setTextColor(mContext.getResources().getColor(R.color.download_btn_blue_style_text));
		}else if(type == BUTTON_GRAY){
			btn.setBackgroundResource(R.drawable.download_button_gray);
			btn.setTextColor(mContext.getResources().getColor(R.color.download_btn_gray_style_text));
		}else if(type == BUTTON_ORANGE){
			btn.setBackgroundResource(R.drawable.download_button_orange);
			btn.setTextColor(mContext.getResources().getColor(R.color.download_btn_orange_style_text));
		}
	}
	
	private void makeUis(DownloadItemUI dlUi, DealingTaskHolder dealingHolder){
		int status = ((DownloadManagerActivity)mContext).getDownloadStatus(dlUi.dlItem.getId(), 
				dlUi.dlItem.getPkgName(), 
				dlUi.dlItem.getVersionCode());
		switch (status) {
//		case DownloadService.STATUS_NO_STATUS://"无";
//			break;
		
		
		case DownloadService.STATUS_PENDING: // "排队中";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.waiting);

			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);

			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_GRAY, dealingHolder.button);
			dealingHolder.button.setText(R.string.waiting);
			dealingHolder.button.setClickable(false);
			break;
			
		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD: //"准备下载";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.prepare_download);
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(true);
			//dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_GRAY, dealingHolder.button);
			dealingHolder.button.setText(R.string.pause);
			dealingHolder.button.setClickable(false);
			
			break;
		case DownloadService.STATUS_DOWNLOADING: //"下载中";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(getSpeedString(dlUi.dlItem));
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_GRAY, dealingHolder.button);
			dealingHolder.button.setText(R.string.pause);
			dealingHolder.button.setClickable(true);
			
			break;
		case DownloadService.STATUS_PREPARE_TO_STOP: //"准备停止";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText("0K/S");
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(true);
			//dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_BLUE, dealingHolder.button);
			dealingHolder.button.setText(R.string.go_on);
			dealingHolder.button.setClickable(false);
			
			break;
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK: // "移动网络等待";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.wait_for_wifi);
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_BLUE, dealingHolder.button);
			dealingHolder.button.setText(R.string.go_on);
			dealingHolder.button.setClickable(true);
			
			break;
		case DownloadService.STATUS_PAUSED_BY_USER: //"用户暂停";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.paused);
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_BLUE, dealingHolder.button);
			dealingHolder.button.setText(R.string.go_on);
			dealingHolder.button.setClickable(true);
			
			break;
		case DownloadService.STATUS_PAUSED_BY_ERROR: //"下载出错";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.download_error);
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText(getProgressString(dlUi.dlItem));
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_ORANGE, dealingHolder.button);
			dealingHolder.button.setText(R.string.retry);
			dealingHolder.button.setClickable(true);
			
			break;
			
//		case DownloadService.STATUS_DOWNLOAD_FINISHED: // "下载完成";
//			break;
			
		case DownloadService.STATUS_CAN_INSTALL: //"准备安装";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.wait_for_install);
			
			dealingHolder.dlProgress.setVisibility(View.INVISIBLE);
			//dealingHolder.dlProgress.setText(R.string.download_over);
			dealingHolder.progressBar.setVisibility(View.INVISIBLE);
			dealingHolder.progressBar.setIndeterminate(false);
			dealingHolder.progressBar.setProgress(100);
			setButtonParam(BUTTON_BLUE, dealingHolder.button);
			dealingHolder.button.setText(R.string.install);
			dealingHolder.button.setClickable(true);
			break;
//		case DownloadService.STATUS_INSTALLED: //"已安装";
//			
//			break;
		case DownloadService.STATUS_INSTALLING: //"安装中";
			AsyncImageLoader.getInstance(mContext).displayImage(dlUi.dlItem.getIconUrl(),
					dealingHolder.appIcon, R.drawable.default_loading_icon, false);
			dealingHolder.appName.setText(dlUi.dlItem.getName());
			dealingHolder.dlStatus.setText(R.string.installing);
			
			dealingHolder.dlProgress.setVisibility(View.VISIBLE);
			dealingHolder.progressBar.setVisibility(View.VISIBLE);
			
			dealingHolder.dlProgress.setText("");
			dealingHolder.progressBar.setIndeterminate(true);
			//dealingHolder.progressBar.setProgress(getProgress(dlUi.dlItem));
			setButtonParam(BUTTON_BLUE, dealingHolder.button);
			dealingHolder.button.setText(R.string.installing);
			dealingHolder.button.setClickable(false);
			break;
		default:
			//return "未知状态:" + status;
			break;
		}
		
	}
	
	private View showUnfinishSection(final DownloadItemUI dlui, int position, View convertView, ViewGroup parent){
		UnfinishSectionHolder unFinishSectionHolder = null;
		if(convertView == null){
			unFinishSectionHolder = new UnfinishSectionHolder();
			convertView = getInflater().inflate(R.layout.dl_mrg_unfinish_section, parent, false);
			unFinishSectionHolder.sectionView = convertView.findViewById(R.id.sectionview);
			convertView.setTag(unFinishSectionHolder);
		}else{
			unFinishSectionHolder = (UnfinishSectionHolder)convertView.getTag();
		}
		String setionStr = mContext.getResources().getString(R.string.dealing);
		setionStr += "(" + dlui.data.toString() + ")";
		unFinishSectionHolder.sectionView.setText(setionStr);
		
		return convertView;
	}
	
	private View showFinishSection(final DownloadItemUI dlui, int position, View convertView, ViewGroup parent){
		FinishSectionHolder finishSectionHolder = null;
		
		if(convertView == null){
			finishSectionHolder = new FinishSectionHolder();
			convertView = getInflater().inflate(R.layout.dl_mrg_finish_section, parent, false);
			finishSectionHolder.titleView = convertView.findViewById(R.id.title_view);
			finishSectionHolder.clearView = convertView.findViewById(R.id.clear_view);
			convertView.setTag(finishSectionHolder);
		}else{
			finishSectionHolder = (FinishSectionHolder)convertView.getTag();
		}
		String setionStr = mContext.getResources().getString(R.string.finish_dl);
		setionStr += "(" + dlui.data.toString() + ")";
		finishSectionHolder.titleView.setText(setionStr);
		finishSectionHolder.clearView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mListener.onClearAllFinishTask();
			}
		});
		
		return convertView;
	}
	
	private View showDownloadFinishTask(final DownloadItemUI dlui, int position, View convertView, ViewGroup parent){
		FinshTaskHolder finishTaskHolder = null;
		if(convertView == null){
			finishTaskHolder = new FinshTaskHolder();
			convertView = getInflater().inflate(R.layout.dl_mrg_finish_item, parent, false);
			finishTaskHolder.appIcon = convertView.findViewById(R.id.dl_app_icon);
			finishTaskHolder.appName = convertView.findViewById(R.id.dl_app_name);
			finishTaskHolder.appTime = convertView.findViewById(R.id.dl_app_time);
			finishTaskHolder.openBtn = convertView.findViewById(R.id.open_app_button);
			convertView.setTag(finishTaskHolder);
		}else{
			finishTaskHolder = (FinshTaskHolder)convertView.getTag();
		}
		
		AsyncImageLoader.getInstance(mContext).displayImage(dlui.dlItem.getIconUrl(),
				finishTaskHolder.appIcon, R.drawable.default_loading_icon, false);
		finishTaskHolder.appName.setText(dlui.dlItem.getName());
		
		//String date = mSd.format(dlui.dlItem.getCreateTime());
		String date = mSd.format(dlui.dlItem.getLastModification());
		finishTaskHolder.appTime.setText(mContext.getResources().getString(R.string.install_at) + date);
		finishTaskHolder.openBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mListener.onAppOpenClick(dlui.dlItem);
			}
		});
		
		return convertView;
	}
	
	private View showDownloadDealingTask(final DownloadItemUI dlui, int position, View convertView, ViewGroup parent){
		DealingTaskHolder dealingHolder = null;
		if(convertView == null){
			dealingHolder = new DealingTaskHolder();
			convertView = getInflater().inflate(R.layout.dl_mrg_dealing_item, parent, false);
			dealingHolder.appIcon = convertView.findViewById(R.id.dealing_app_icon);
			dealingHolder.appName = convertView.findViewById(R.id.dealing_app_name);
			dealingHolder.dlStatus = convertView.findViewById(R.id.dl_status);
			dealingHolder.dlProgress = convertView.findViewById(R.id.dl_schedule);
			dealingHolder.progressBar = convertView.findViewById(R.id.dl_progressbar);
			dealingHolder.button = convertView.findViewById(R.id.dealing_button);
			dealingHolder.delete = convertView.findViewById(R.id.delete_task);
			convertView.setTag(dealingHolder);
		}else{
			dealingHolder = (DealingTaskHolder)convertView.getTag();
		}
		makeUis(dlui, dealingHolder);
		
		dealingHolder.button.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				mListener.onDealingBtnClick(dlui.dlItem);
			}
		});
		
		dealingHolder.delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mListener.onDeleteOneDlItem(dlui.dlItem);
				
			}
		});
		
		return convertView;
	}

}
